package cn.wolfcode.wolf2w.resolver;

import cn.wolfcode.wolf2w.annotation.UserParam;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.IUserInfoRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户参数解析器
 * 把当前用户对象，注入到请求映射方法中 UserInfo 类型的参数变量中
 */
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    // 设置当前解析器支持解析什么类型的参数
    // 此处设置支持解析的参数类型是 UserInfo
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        // 如果参数类型是UserInfo，并且贴了 UserParam 注解，才返回true
        return parameter.getParameterType() == UserInfo.class && parameter.hasParameterAnnotation(UserParam.class);
    }

    // 执行这个方法的前提，上面的这个方法必须返回true，因为要支持，才有必要注入
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        // 解析参数并注入参数值
        // 获取当前登录用户对象，并注入映射方法的UserInfo 参数变量中
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        String token = request.getHeader("token");
        UserInfo user = userInfoRedisService.getUserByToken(token);
        // springmvc会自动将返回值注入到 UserInfo 对象中
        return user;
    }
}
